var express = require('express');
var router = express.Router();
var { userModel,roleModel,rightModel,companyModel,articleModel,commentModel } = require('../model/dbs')
const jwt = require('jsonwebtoken')
//注册接口
router.post('/register',async (req,res)=>{
  let name = req.body.name
  let phone = req.body.phone
  let password = req.body.password
  let canreg = await userModel.findOne({name:name})
  if(canreg){
    res.send({code:401,msg:'用户名已存在'})
  }else{
    await userModel.create({name:name,phone:phone,password:password})
    res.send({code:200,msg:'注册成功'})
  }
})
//登录接口
router.post('/login',async function(req, res) {
  let phone = req.body.phone
  let password = req.body.password
  let hasPhone = await userModel.findOne({phone:phone})
  if(!hasPhone){
    res.send({code:'401',msg:'该手机号未注册'})
  }
  let pwd = await userModel.findOne({phone:phone,password:password})
  if(!pwd){
    res.send({code:'402',msg:'密码错误'})
  }
  let canLogin = await userModel.findOne({phone:phone,password:password,state:true})
  if(!canLogin){
    res.send({code:'403',msg:'此账号已被禁用请联系管理员'})
  }
  let user = await userModel.findOne({phone:phone,password:password,state:true}).populate('roleId').populate('articleId').populate('like')
  let token =  'Bearer '+jwt.sign({ phone: phone }, 'wyt', { expiresIn: '1d' })
  res.send({code:200,msg:'登录成功',user,token})
});
router.get('/info',async (req,res)=>{
  let user = await userModel.findOne({phone:13273102959,}).populate('roleId').populate('articleId').populate('like')
  res.send({code:200,msg:'登录成功',user})
})

module.exports = router;
